from CourseScheduling.blueprints.schedule.dbHelper import getInfo, getMajorsNames, getMajorSpecsByName, getQuarterCodes, getSchedule, getAllSpecs
from flask import Blueprint, render_template, request
from CourseScheduling.blueprints.schedule.models import Course, Major
import lib.CourseSchedulingAlgorithm as cs
import ast
from CourseScheduling.blueprints.schedule import dgw_data
from CourseScheduling.blueprints.schedule.forms import HomeInputForm

schedule = Blueprint('schedule', __name__, template_folder='templates')

@schedule.route('/')
def index():
    return render_template('schedule/index.html')

@schedule.route('/input', methods=['GET', 'POST'])
def schedule_home():
    """
    input page 1 for major selection
    """
    home_input_form = HomeInputForm()
    home_input_form.firstQuarter.choices=getQuarterCodes()
    majorNames = getMajorsNames()
    specNames = getAllSpecs()
    home_input_form.majors.choices=list(map(lambda x: (x,x), majorNames))
    home_input_form.specs.choices=list(map(lambda x: (x,x), specNames))
    if home_input_form.next.data:
        print("has data")
        if home_input_form.validate_on_submit():
            print(home_input_form.firstQuarter.raw_data)
        else:
            print ("not validated")
            print(home_input_form.firstQuarter.raw_data)

    return render_template('schedule/input.html',form=home_input_form)

@schedule.route('/validateinput', methods=['POST'])
def validate_input():
    pass

@schedule.route('/detailedinput', methods=['POST', 'GET'])
def detailed_input():
    form = request.form
    major = form.getlist("major")[0].upper()
    print("MAJOR: " + major)
    return render_template('schedule/detailedinput.html',
                            specs=getMajorSpecsByName(major))


@schedule.route('/saveme')
def saveme():
    return render_template('schedule/saveme.html')

@schedule.route('/launch', methods=['POST', 'GET'])
def launch():
    # get cookie and parse xml
    cookie = request.form.getlist('cookie')[0]
    d = dgw_data.data(cookie)
    d.fetch_xml()

    # input settings 
    upper_units = 90
    max_widths = {0: 13, 'else': 16}
    startQ = 0
    avoid = set()
    taken = d.classes
    spec = d.spec
    ge_filter = d.ge_table
    majors = d.major

    L, max_row_length = getSchedule(upper_units, max_widths, startQ, avoid, taken, spec, ge_filter, majors)
    courses_preview = []
    for quarter in L.L:
        for course in quarter:
            courses_preview.append(course)
    courses_preview.sort()

    return render_template('schedule/preview.html',
                          courses=courses_preview, quarter=startQ, specialization=spec[0], taken=str(taken))



@schedule.route('/output', methods=['POST', 'GET'])
def schedule_output():
    # user info should be private
    # also user info could be too large for GET request
    if request.method != 'POST':
        return render_template('schedule/input.html')

    form = request.form

    # input will be provided by POST request.
    # config upper standing units
    upper_units = 90
    # start quarter
    startQ = int(form.getlist("quarter")[0])
    # set of courses taken
    #taken = set(ast.literal_eval(form.getlist("finished")[0])) #{'MATH1B'}
    taken = set(ast.literal_eval(form.getlist("taken")[0]))
    # width setting
    max_widths = {0: 13, 'else': 16}
    # avoid
    avoid = set(ast.literal_eval(form.getlist("finished")[0])) #{'COMPSCI141'}
    #avoid = {}
    # union universal and cs general requirements (default)
    majors = form.getlist("majors")
    ge_filter = {}

    L, max_row_length = getSchedule(upper_units, max_widths, startQ, avoid, taken, spec, ge_filter, majors)

    # the parameters for render_template will be provided by CourseSchedulingAlgorithm:
    #   1,  L : best schedule generated by the algorithm
    #   2,  max_row_length : the max length of a row in this schedule

    return render_template('schedule/output.html',
                           schedule=L, row_length=max_row_length)


@schedule.route('/preview', methods=['POST', 'GET'])
def schedule_preview():
    # user info should be private
    # also user info could be too large for GET request
    if request.method != 'POST':
        return render_template('schedule/input.html')

    form = request.form

    # quarters width in format {quarter_id : units}
    quarters = dict(ast.literal_eval(form.getlist("quarters")[0]))
    print ("quarters", quarters)

    # input will be provided by POST request.
    # config upper standing units
    upper_units = 90
    # start quarter
    startQ = int(form.getlist("firstQuarter")[0])
    # width setting
    max_widths = {0: 200, 'else': 200}

    spec = form.getlist("specs")
    
    majors = form.getlist("majors")
    ge_filter = {}
    taken = set()
    avoid = set()

    L, max_row_length = getSchedule(upper_units, max_widths, startQ, avoid, taken, spec, ge_filter, majors)

    courses_preview = []
    for quarter in L.L:
        for course in quarter:
            courses_preview.append(course)
    courses_preview.sort()

    # the parameters for render_template will be provided by CourseSchedulingAlgorithm:
    #   1,  L : best schedule generated by the algorithm
    #   2,  max_row_length : the max length of a row in this schedule

    return render_template('schedule/preview.html',
                           courses=courses_preview, quarter=startQ, specialization=spec, taken=str(taken))
